package com.pig.graduate.util;

import cn.hutool.core.util.ObjectUtil;
import com.pig.graduate.common.anno.PropertyMsg;
import com.pig.graduate.common.exception.MyException;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class BeanUtil<T> {

    public String changeBeanStr(Object oldBean,Object newBean){
        T old = (T)oldBean;
        Field[] fields = old.getClass().getDeclaredFields();
        List<Field> list = Arrays.asList(fields);
        StringBuffer str = new StringBuffer();
        final int[] i = {1};
        list.forEach(field -> {
            field.setAccessible(true);
            if(field.isAnnotationPresent(PropertyMsg.class)){
                try{
                    Object newValue = field.get(newBean);
                    Object oldValue = field.get(oldBean);
                    if(ObjectUtil.notEqual(oldValue,newValue)){
                        str.append(i[0]+","+field.getAnnotation(PropertyMsg.class).value() + ":")
                                .append("修改前->" + oldValue + "，修改后->" + newValue + "\n");
                        i[0]++;
                    }
                } catch (Exception e){
                    throw new MyException("比对Bean属性失败");
                }
            }
        });
        return str.toString();
    }
}
